let app = getApp();
let location = require("../../../mybehaviors/location/location");
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    storeId:0,
    iPnoneBottomBol:false, //是否是苹果手机
    posterImg:'',
    workTime:'', //营业日期
    posterShow:false, //海报弹窗
    consultShow: false, //咨询弹窗
    collectChecked:0, //是否收藏
    storePage:1,
    storeLastPage:0,
    storeMore:false,
    addressDetail:'',
    couponStore: {},
    loveName: '', //爱心值别名
    pointName: '', //积分别名
    commercialTab:[
      {
        name:'到店优惠',
        status:0,
      },
      {
        name:'堂食点单',
        status:1,
      },
      {
        name:'打包自取',
        status:2,
      },
      {
        name:'外卖',
        status:3,
      }
    ],
    storeDetail:{}, //商户详情
    storeGoodsList:[],
    workWeek:[ //显示选中的日期数组
      {
        title: '周一',
        value: '1'
      },
      {
        title: '周二',
        value: '2'
      },
      {
        title: '周三',
        value: '3'
      },
      {
        title: '周四',
        value: '4'
      },
      {
        title: '周五',
        value: '5'
      },
      {
        title: '周六',
        value: '6'
      },
      {
        title: '周日',
        value: '7'
      }
    ],
    latitude:'',
    longitude:'',
    //客服插件
    customerOpen: false, //客服弹窗开关
    serviceShow: false,
    serviceQRcode: '',
    serviceMobile: '',
    cservice: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if((options.storeId??'') !== '') {
      this.data.storeId = parseInt(options.storeId);
    }
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        let info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if(chil_arr[0] == "storeId") {
            this.setData({
              storeId: chil_arr[1]
            })
          }
        }
      }
    }

    try {
      wx.removeStorageSync('applyaddresspoint');
    } catch (e) {
      // Do something when catch error
    }
    this._getLocation((mapdata, e) => {
      this.setData({
        longitude: e.lng,
        latitude: e.lat
      });
      this.storeDetail();
    });
    this.storeGoodsList();
    this.serviceDetail();
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    try {
      let value = wx.getStorageSync('applyaddresspoint');
      if (value) {
        this.setData({
          longitude: value.point.lng,
          latitude: value.point.lat
        });
        // Do something with return value
      }
    } catch (e) {
      console.log(e);
    }
  },
  onBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  getiPnoneBottom() {
    let that = this;
    try {
      let value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  shareHint() {
    wx.showToast({
      icon: "none",
      title: '长按图片分享好友',
      duration: 3000,
    });
  },
  saveImg() {  //保存图片
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功');
            }
          });
        }
      }
    });
    var imgSrc = this.data.posterImg;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            });
          },
          fail: function (err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权");
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限成功,再次长按保存图片',
                      duration: 1500
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限失败,保存图片需要用户授权',
                      duration: 1500
                    });
                  }
                }
              });
            }
          },
          complete(res) {
            console.log(res);
          }
        });
      }
    });
  },
  storeGoodsList() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.store.storeGoodsList");
    let json = {
      basic_info:1,
      store_id: this.data.storeId,
      page:this.data.storePage,
      paginate:3
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success: function (resdata) {
        let res = resdata.data;
        if (res.result == 1) {
          if (!that.data.storeLastPage) {
            that.data.storeLastPage = 0;
          }
          that.setData({
            storeGoodsList:res.data.data,
            storeMore:true,
            storeLastPage: res.data.last_page,
            loveName: res.basic_info?.love,
            pointName: res.basic_info?.point
          })
        } else {
          this.data.storePage = this.data.storePage - 1;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  storeDetail() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.store.storeDetail");
    let json = {
      store_id: this.data.storeId,
      longitude: this.data.longitude,
      latitude: this.data.latitude
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success: function (resdata) {
        let res = resdata.data;
        if (res.result == 1) {
          let addressDetail = `${res.data.city}${res.data.district}${res.data.street}${res.data.address}`,
              workWeek = res.data.work_week,
              workWeekData = that.data.workWeek,
              weekList =[];
              weekList = workWeekData.filter(item => workWeek.indexOf(item.value) > -1); //筛选选中的日期
          let workTimeTitle =  `${ weekList[0].title}至${weekList[weekList.length -1].title}`;
          that.setData({
            storeDetail: res.data,
            addressDetail: addressDetail,
            workTime: workTimeTitle,
            collectChecked: res.data.is_collection
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onCollect() {
    this.setData({
      collectChecked: this.data.collectChecked===0?1:0
    });
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.collection.storeCollect");
    let json = {
      store_id: this.data.storeId,
      status:this.data.collectChecked
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success: function (resdata) {
        let res = resdata.data;
        wx.showToast({
          icon: 'none',
          title: res.msg,
          duration: 1500
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onCommercialTo() { //跳转商户信息
    wx.navigateTo({
      url: `/packageF/consumption/commercial/commercial?storeId=${this.data.storeId}`
    })
  },
  programNav(event) {
    let navTo = event.currentTarget.dataset.navto;
    wx.navigateTo({
      url: navTo
    })
  },
  goodsDetail(event) {
    let goodId = event.currentTarget.dataset.itemid;
    wx.navigateTo({
      url: `/packageF/consumption/goodsDetails/goodsDetails?goodsId=${goodId}`
    })
  },
  phone(e) {
    let phoneNum = this.data.storeDetail.store_mobile;
    wx.makePhoneCall({
      phoneNumber: phoneNum, //仅为示例，并非真实的电话号码
    });
  },
  storePoster() { //海报信息设置
    let that = this;
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.poster.storePoster");
    let json = {
      store_id: this.data.storeId,
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success: function (resdata) {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({
            posterImg:res.data.url
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  serviceDetail() {  //客服插件开关
    let goods_id = this.data.goodsId;
    let urlStr = app.getNetAddresss("goods.customer-service.index");
    app._postNetWork({
      url: urlStr,
      data: {
        goods_id: goods_id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            customerOpen:res.data.customer_open,
            showKefu: true,
            cservice: res.data.cservice,
            serviceQRcode: res.data.service_QRcode,
            serviceMobile: res.data.service_mobile,
            
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  showPop() { //打开客服弹窗
    let setServicePlugin = app._isTextEmpty(this.data.serviceQRcode) && app._isTextEmpty(this.data.serviceMobile);
    if (app._isTextEmpty(this.data.cservice) && setServicePlugin) {
      return app.tips("抱歉，暂未设置客服信息");
    }
    if (!app._isTextEmpty(this.data.cservice) && setServicePlugin) {
      this.gotoChat({
        currentTarget: {
          dataset: {
            cservice: this.data.cservice
          }
        }
      }) //只设置了客服链接，直接跳转
      return;
    }
    this.setData({
      serviceShow: true,
    });
  },
  gotoChat(evt) { //客服跳转
    let url = evt.currentTarget.dataset.cservice + "&goods_id=" + this.data.goodsId;
    wx.navigateTo({
      url: url,
      fail: (err) => {
        app.tips("客服路由出错");
      }
    });
  },
  tapIndex() { //首页跳转
    wx.redirectTo({
      url: '/packageG/index/index',
    })
  },
  closePop() {
    this.setData({
      serviceShow: false,
    });
  },
  onClose() {
    this.setData({
      posterShow: false,
      consultShow: false
    })
  },
  goodsMoreData() {
    this.data.goodsMore = false; // 防止多次请求分页数据
    if (this.data.storePage >= this.data.storeLastPage) {
      return;
    } else {
      this.setData({
        storePage: this.data.storePage + 1
      })
      let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.store.storeGoodsList");
      let json = {
        store_id: this.data.storeId,
        page: this.data.storePage,
        paginate:3
      };
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.goodsMore = true;
            this.setData({
              storeGoodsList : this.data.storeGoodsList.concat(list),
              storeLastPage: res.data.last_page
            })
          } else {
            this.data.goodsPage = this.data.goodsPage - 1;
            // this.goodsMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  navigation(event) { //查看商家的地址定位信息
    let latitude = event.currentTarget.dataset.latitude;
    let longitude = event.currentTarget.dataset.longitude;
    let point = app.BMapTransqqMap(parseFloat(longitude), parseFloat(latitude));
    wx.openLocation({
      latitude: point.lat,
      longitude: point.lng,
      name: this.data.storeDetail?.store_name,
      scale: 18
    });
  },
  onConsultClose() {
    this.setData({
      consultShow: false
    })
  },
  onConsult() {
    this.setData({
      consultShow: true
    })
  },
  onPosterClick() {
    this.setData({
      posterShow: true
    })
    this.storePoster();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})